
package com.base.pagination;

import java.io.Serializable;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 * 查询条件类
 */
public abstract class Condition implements Serializable, Cloneable {

	private static final long serialVersionUID = -7448688547460880575L;

	private String orderByItem = "";  //排序
	private String groupByItem = "";  //分组
	
	private int pageSize = Page.DEFAULT_PAGE_SIZE;  //一页包含的记录数
	private int pageNo =1;  //默认当前页
	
	

	public Object clone() {
		Condition o = null;
		try {
			o = (Condition) super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return o;
	}
	
	public String getGroupByItem() {
		return groupByItem;
	}

	public void setGroupByItem(String groupByItem) {
		this.groupByItem = groupByItem;
	}

	public String getOrderByItem() {
		return orderByItem;
	}

	public void setOrderByItem(String orderByItem) {
		this.orderByItem = orderByItem;
	}

	public abstract String getInitialHql();

	public String getCompleteHql() {
		String completeHql = getInitialHql();
		if (!orderByItem.equals(""))
			completeHql += " order by " + orderByItem;
		if (!groupByItem.equals(""))
			completeHql += " group by " + groupByItem;
		return completeHql;
	}

	
	public Query getHibernateQuery(Session session){
		Query query = session.createQuery(this.getCompleteHql());
		query = this.preparedParams(query);
		return query;	
	}
	
	public Query getHibernateCountQuery(Session session){
		String countHql = "select count(*) " + trimSelect(this.getInitialHql());
		Query query = session.createQuery(countHql);
		query = this.preparedParams(query);
		return query;
	}
	
	private String trimSelect(String hql){
		int index = StringUtils.indexOf(hql,"from");
		hql = StringUtils.mid(hql, index,hql.length());
		return hql;
	}
	public Query preparedParams(Query query){return query;}; 

	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

}
